package com.example.usermanager.controller;

import com.example.usermanager.mapper.UserMapper;
import com.example.usermanager.model.UserInfo;
import com.example.usermanager.tools.AppFinal;
import com.example.usermanager.tools.ResponseBody;
import com.example.usermanager.tools.SessionUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:咭咭熊
 * Date:2021 - 07 - 25
 * Time:19:16
 */

/**
 *    @Resource//将某个类注入到当前的类当中
 *    @RequestMapping("/user")//定义当前类的映射
 *    @RequestParam——参数不能为空
 */
/***
 * 返回原则——所有的接口必须有统一的返回格式
 * 常见返回字段：
 * （1）返回状态——status
 * （2）数据——data
 * （3）信息——message
 * 实现方法：
 * （1）定义一个全局的返回对象，每个接口返回时调用此对象进行返回；
 * （2）【Spring】中的Advice接口始兴县统一的数据封装
 */
//2.定义统一的返回格式——定义统一的返回对象

@RestController
@RequestMapping("/user")//定义当前类的映射
public class UserController {

    @Resource//将某个类注入到当前的类当中
    private UserMapper userMapper;

    //1.登录方法
    @RequestMapping("/login")//设置路由
//    public UserInfo login(@RequestParam String username,@RequestParam String password){
    public ResponseBody<UserInfo> login(@RequestParam String username,
                                        @RequestParam String password,
                                        HttpServletRequest request){
        UserInfo userInfo = userMapper.login(username,password);//进行数据库查询
        int status = -1;
        String message = "用户名或者密码错误！";
        if(userInfo != null &&userInfo.getId() > 0){
            status = 0;
            message = "";
            //登录成功之后将用户对象信息存储到session中——便于验证时进行读取
            HttpSession session = request.getSession();//参数默认为true——当没有session时候进行创建session

            session.setAttribute(AppFinal.USERINFO_SESSION_KEY,userInfo);


        }
        return new ResponseBody<>(status,message,userInfo);
    }


    //2.查询当前登录用户的权限——检验是否是管理员
    @RequestMapping("/checkadmin")
    public ResponseBody<Integer> checkAdmin(HttpServletRequest request){
        int data = 0;
        //从session中获取信息
        HttpSession session= request.getSession(false);//设置为false，当session中没有信息时就会进行创建
        UserInfo userInfo =null;
        if(session != null &&
                (userInfo = (UserInfo)session.getAttribute(AppFinal.USERINFO_SESSION_KEY ))!= null){

            data = userInfo.getIsadmin();
        }
        return new ResponseBody<>(0,"",data);

    }

    //3.添加信息
    @RequestMapping("/add")
    public ResponseBody<Integer> add(UserInfo userInfo,HttpServletRequest request ){
        int data = 0;//表示添加失败
        int status = 0;
        String message = "";
        //安全校验
        UserInfo user = SessionUtil.getUserBySession(request);
        if(user == null) {
            //未登陆状态
            status = -1;
            message = "当前用户未登录，请先登录！";
        } else if(userInfo.getIsadmin() == 1){//要添加超级管理员
            if(user.getIsadmin() == 0) {
                status = -2;
                message = "当前登录用户权限不足，不能操作";
            }else if(user.getIsadmin() == 1){
                //当前登录用户为超级管理员
                data = userMapper.add(userInfo);
                status = 0;
            }
        }else if(userInfo.getIsadmin() == 0){//添加一个普通管理员
            data = userMapper.add(userInfo);
        }

        return new ResponseBody<>(status,message,data);

    }

    //4.获取用户信息
    @RequestMapping("/getuser")
    public ResponseBody<UserInfo> getUser(@RequestParam int uid){

        int status = -1;
        String message = "未知错误！";
        UserInfo userinfo = userMapper.getUser(uid);
        if(userinfo != null){
            //todo:权限校验
            status = 0;

        }
        return new ResponseBody<>(status,message,userinfo);

    }

    //5.修改用户信息
    @RequestMapping("/update")
    public ResponseBody<Integer>eupdate(UserInfo userInfo){

        int data = 0;
        //todo:权限校验
        data = userMapper.update(userInfo);
        return new ResponseBody<>(0,"",data) ;
    }

    //6.组合条件查询
    @RequestMapping("/list")
    public  ResponseBody<HashMap<String,Object>> getList(String name,
                                                         String address,
                                                         String email,
                                                         int cpage,
                                                         int psize,
                                                         HttpServletRequest request){
        //（1）权限校验
        UserInfo userInfo = SessionUtil.getUserBySession(request);
        if(userInfo == null){
            //未登录
            return new ResponseBody<>(-1,"当前用户未登录!",null);
        }
        //(2)判断权限
        Integer isadmin = null;
        if(userInfo.getIsadmin() == 0){
            isadmin = 0;

        }
        //处理前端的查询参数
        name = name.equals("") ? null : name;
        address = address.equals("") ? null : address;
        email = email.equals("")? null : email;

        //3.构建分页查询字段 limit xx psize查询当前页面的列表信息
        //跳过查询的条数
        int skipCount = (cpage - 1) * psize;
        //查询一页的列表信息
        List<UserInfo> list = userMapper.getListByPage(name,address,email,skipCount,psize,isadmin);
        //4.查询满足条件的数据总条数
        int tcount = userMapper.getCount(name,address,email,isadmin);
        //总页数
        int tpage = (int) Math.ceil(tcount/(psize * 1.0));
        //封装统一返回对象
        HashMap<String,Object> data = new HashMap<>();
        data.put("list",list);
        data.put("tcount",tcount);//总条数
        data.put("tpage",tpage);//总页数
        return new ResponseBody<>(0,"",data);


    }

    //7.单条删除
    @RequestMapping("/del")
    public  ResponseBody<Integer> del(@RequestParam int id ,HttpServletRequest request){
        //权限校验
        UserInfo userInfo = SessionUtil.getUserBySession(request);
        if(userInfo == null){
            //未登陆
            return  new ResponseBody<>(-1,"未登陆！",0);
        }
        //判断删除的是否是自己
        if(id == userInfo.getId()){
            //删除的是自己
            return new ResponseBody<>(-2,"不可以删除自己！",0);
        }
        //权限校验
        Integer isadmin = null;
        if(userInfo.getIsadmin() == 0){
            isadmin = 0;
        }
        int result = userMapper.del(id,isadmin);
        return  new ResponseBody<>(0,"",result);

    }

    //8.多条数据的删除
    @RequestMapping("/dels")
    public ResponseBody<Integer> dels(String ids){
        int result= 0;
        result = userMapper.dels(ids.split(","));
        System.out.println("ids:" + ids);
        return new ResponseBody<>(0,"",result);

    }




}
